package com.viroyal.monitorlib.receiver;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import com.hwangjr.rxbus.RxBus;
import com.suntiago.baseui.utils.log.Slog;
import com.viroyal.monitorlib.entity.DownloadEntry;
import com.viroyal.monitorlib.entity.rx.RxInstall;
import com.viroyal.monitorlib.notify.DataChanger;
import com.viroyal.monitorlib.utils.Constants;
import com.viroyal.monitorlib.utils.SPUtils;

import java.util.List;

/**
 * Created by cxy_nj on 2016/9/1.
 */
public class InitApkBroadCastReceiver extends BroadcastReceiver {

    private static final String TAG = "InitApkBroadCastReceive";

    @Override
    public void onReceive(Context context, Intent intent) {
        String packageName = intent.getDataString().substring("package:".length());
        Slog.d(TAG, "onReceive  [context, intent]:" + intent.getAction().toString());
        if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)
                || intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
            String url = SPUtils.getInstance(context).get(Constants.APK_URL);
            Slog.d(TAG, "onReceive  [context, intent] packageName :" + packageName);
            if (!TextUtils.isEmpty(url) &&
                    DataChanger.getInstance(context).containsDownloadEntry(url)) {
                Slog.d(TAG, "onReceive  [context, intent] packageName :" + packageName + "安装完成");
                DownloadEntry downloadEntry = DataChanger.getInstance(context).queryDownloadEntryByUrl(url);
                if (downloadEntry != null && downloadEntry.percent >= 100) {
                    Slog.d(TAG, "onReceive  [context, intent] packageName :" + packageName + "安装完成->打开");
                    downloadEntry.reset();//结束之后删除本地apk（安装结束之后）
                    DataChanger.getInstance(context).deleteDownloadEntryByUrl(url);
                    startApplicationWithPackageName(context, packageName);
                }
            }
            RxBus.get().post(new RxInstall(packageName, "install", true));
        } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
            Slog.d(TAG, "onReceive  [context, intent] packageName :" + packageName);
            RxBus.get().post(new RxInstall(packageName, "uninstall", true));
        }

    }

    public void startApplicationWithPackageName(Context context, String packagename) {
        Slog.d(TAG, "onReceive  [context, intent] startPackageName :" + packagename);
        PackageInfo packageinfo = null;

        try {
            packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (packageinfo == null) {
            return;
        }

        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);
        Slog.d(TAG, "onReceive  [context, intent] PackageInfo :" + packageinfo.packageName);
        List<ResolveInfo> resolveinfoList = context.getPackageManager().queryIntentActivities(resolveIntent, 0);
        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            Slog.d(TAG, "onReceive  [context, intent] IntentStartPackage:" + resolveinfo.activityInfo.packageName);
            String packageName = resolveinfo.activityInfo.packageName;
            String className = resolveinfo.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

}
